<template>
  <el-form-item :label="label" :disabled="disabled" :type="type" :prop="prop" :rules="rules" :api="api" :class="clazz" >
    <el-autocomplete
      v-model="model"
      :value="value"
      :fetch-suggestions="querySearch"
      :placeholder="placeholder"
      clearable
      style="width:100%"
      @change="$emit('change')"
      @select="handleSelect"
    />
  </el-form-item>

</template>

<script>
import request from '@/utils/request'
export default {
  name: 'HtInputSelect',
  props: {
    prop: String,
    rules: [Object, Array],
    value: '',
    label: '',
    clazz: '',
    api: {
      type: String,
      default: '/pcc/core/biz/getCurrTypeValList'
    },
    disabled: Boolean,
    append: String,
    type: String,
    dataSource: {
      type: String,
      default: '[]'
    },
    placeholder: ''
  },
  data() {
    return {
      restaurants: [],
      visible: false,
      interval: null,
      model: ''
    }
  },
  watch: {
    value(val) {
      this.model = val
    },
    model: function() {
      this.$emit('input', this.model)
    }
  },
  mounted() {
    this.getData()
    if (this.type && this.$store.state.baseData[this.type].length > 0) {
      this.restaurants = this.$store.state.baseData[this.type]
    } else if (this.dataSource) {
      this.restaurants = JSON.parse(this.dataSource)
    }
  },
  methods: {
    getData() {
      if (this.$store.state.baseData[this.type]) {
        if (this.$store.state.baseData[this.type].length <= 0) {
          this.getBaseData(this.type)
        }
      }
    },
    getBaseData(typeCode) {
      request({
        url: this.api,
        method: 'post',
        data: {
          typeCode: this.type,
          version: 'latest'
        }
      }).then(res => {
        if (res.returnCode === '0000') {
          this.restaurants = this.change2List(res.data)
          this.$store.commit(typeCode, this.change2List(this.restaurants))
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    change2List(da) {
      var list = []
      da.forEach((item) => {
        list.push({ value: item.name })
      })
      return list
    },
    querySearch(queryString, cb) {
      // var restaurants = this.restaurants
      // var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(this.restaurants)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect(item) {
      this.model = item.value
      this.$emit('input', this.model)
    }
  }
}
</script>
